import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 协议解析功能快速测试
 * 验证十六进制消息解析的正确性
 */
public class ProtocolTest {
    
    public static void main(String[] args) {
        System.out.println("=== IoT协议解析功能测试 ===");
        System.out.println();
        
        // 测试消息
        String[] testMessages = {
            "0000000161C0A5F009F6177F",  // 示例消息
            "0000000A61C0A5F00BB81770",  // 设备10, 30.00°C, 60.00%
            "00000064622A7B000FA01388"   // 设备100, 40.00°C, 50.00%
        };
        
        for (int i = 0; i < testMessages.length; i++) {
            System.out.println("测试消息 " + (i + 1) + ": " + testMessages[i]);
            parseAndDisplay(testMessages[i]);
            System.out.println();
        }
        
        System.out.println("✅ 协议解析功能测试完成！");
    }
    
    /**
     * 解析并显示消息内容
     */
    private static void parseAndDisplay(String hexMessage) {
        try {
            // 验证消息长度
            if (hexMessage.length() != 24) {
                System.out.println("❌ 错误: 消息长度不正确 (" + hexMessage.length() + "/24)");
                return;
            }
            
            // 解析各个字段
            String deviceIdHex = hexMessage.substring(0, 8);
            String timestampHex = hexMessage.substring(8, 16);
            String temperatureHex = hexMessage.substring(16, 20);
            String humidityHex = hexMessage.substring(20, 24);
            
            // 转换为实际值
            long deviceId = Long.parseUnsignedLong(deviceIdHex, 16);
            long timestamp = Long.parseUnsignedLong(timestampHex, 16);
            int temperatureInt = Integer.parseUnsignedInt(temperatureHex, 16);
            int humidityInt = Integer.parseUnsignedInt(humidityHex, 16);
            
            double temperature = temperatureInt / 100.0;
            double humidity = humidityInt / 100.0;
            
            LocalDateTime dateTime = LocalDateTime.ofInstant(
                Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
            
            // 显示解析结果
            System.out.println("  设备ID: DEVICE_" + String.format("%08d", deviceId));
            System.out.println("  时间戳: " + dateTime);
            System.out.println("  温度: " + String.format("%.2f°C", temperature));
            System.out.println("  湿度: " + String.format("%.2f%%", humidity));
            
            // 验证数据范围
            if (temperature >= -50 && temperature <= 80) {
                System.out.println("  ✅ 温度范围正常");
            } else {
                System.out.println("  ⚠️  温度超出范围");
            }
            
            if (humidity >= 0 && humidity <= 100) {
                System.out.println("  ✅ 湿度范围正常");
            } else {
                System.out.println("  ⚠️  湿度超出范围");
            }
            
        } catch (Exception e) {
            System.out.println("❌ 解析失败: " + e.getMessage());
        }
    }
}